<template>
  <div class="changeinfo">
    <van-nav-bar
      title="修改个人信息"
      left-text="返回"
      right-text="Mine"
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight"
    />
    <van-uploader :after-read="afterRead" class="zz">
      <template #default>
        <img :src="user.avatar" alt="" class="me6" />
      </template>
    </van-uploader>
    <van-form @submit="onSubmit">
      <!-- 昵称 -->
      <van-field
        class="mt10"
        v-model="user.nickName"
        name="nickName"
        label="昵称"
        :placeholder="user.nickName ? user.nickName : user.userName"
        :rules="[{ required: false, message: '请填写用户名' }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>
<script>
import { Toast } from "vant";
import { getuser, setuserinfo, imgUpdateAPI } from "@/api/user";

export default {
  data() {
    return {
      user: {},
    };
  },
  computed: {},
  watch: {},

  methods: {
    onClickLeft() {
      this.$router.go(-1);
      Toast("返回");
    },
    onClickRight() {
      this.$router.push("Mine");
      Toast("按钮");
    },
    // async
    afterRead(file) {
      //上传图片格式文件时 若直接上传  图片的二进制字符串过长无法正确上传  所以  使用FormData表单进行加工
      // const data = new FormData();  data.append("file", file.file);
      //把图片加入到表单文件流的末尾 然后在上传
      // const data = new FormData();
      // console.log(file);
      // data.append("file", file.content);
      // console.log(data);
      // const res = await imgUpdateAPI(data);
      // this.user.avatar = res.data;
      // console.log(res.data);
      // console.log(this.user.avatar);
      this.user.avatar = file.content;
    },
    async onSubmit() {
      const res = await setuserinfo({
        nickName: this.user.nickName,
        avatar: this.user.avatar,
      });
      // console.log(res);
      if (res.code == "success") {
        Toast.success(res.message);
        setTimeout(() => {
          this.$router.push("Mine");
        }, 500);
      } else {
        Toast.fail(res.message);
      }
    },
  },
  async created() {
    let res = await getuser();
    console.log(res);
    this.user = res;
  },
  mounted() {},
  components: {},
};
</script>
<style scoped>
.zz {
  display: block;
  padding-top: 20px;
  padding-bottom: 20px;
  background-image: linear-gradient(
    180deg,
    rgba(207, 232, 255, 1) 0,
    rgba(207, 232, 255, 1) 0,
    rgba(143, 107, 170, 1) 100%,
    rgba(143, 107, 170, 1) 100%
  );
  padding-left: 50%;
}
/* .van-uploader__wrapper .van-uploader__input-wrapper {
  position: relative;
  left: 50%;
  transform: translateX(-50%);
} */
.van-field {
  width: 100%;
  font-size: 20px;
}
.mt10 {
  margin-top: 10px;
}
.me6 {
  width: 25vw;
  height: 25vw;
  transform: translateX(-50%);
  border-radius: 50%;
}
</style>
